package com.taoes.simpledocker.controller;

import com.github.dockerjava.api.DockerClient;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.taoes.simpledocker.config.DockerClientFactory;
import com.taoes.simpledocker.model.DockerEndpoint;
import com.taoes.simpledocker.model.ResponseModel;
import com.taoes.simpledocker.service.DockerEndpointService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * TODO: please input file info
 *
 * @author 枕上江南 zhoutao825638@vip.qq.com
 * @date 2021/12/4 11:35 下午
 */
@ApiSort(value = 1)
@Api(tags = "Docker客户端")
@RestController
@RequestMapping("/api/endpoint")
@RequiredArgsConstructor
public class ClientController {

    private final DockerEndpointService dockerEndpointService;

    private final DockerClientFactory clientFactory;


    @ApiOperation("Docker端列表")
    @GetMapping
    public ResponseModel<List<DockerEndpoint>> list() {
        return ResponseModel.ok(dockerEndpointService.list());
    }

    @ApiOperation("删除DockerEndpoint")
    @DeleteMapping("/delete/{clientId}")
    public ResponseModel<Boolean> delete(@PathVariable String clientId) throws Exception {
        dockerEndpointService.delete(clientId);
        clientFactory.refreshClientGroup();
        return ResponseModel.ok(Boolean.TRUE);
    }

    @ApiOperation("修改DockerEndpoint")
    @ApiOperationSupport(ignoreParameters = {"latestTestTime","createdAt","updatedAt"})
    @PostMapping("/update")
    public ResponseModel<Boolean> updateDockerEndpoint(@RequestBody DockerEndpoint dockerEndpoint) throws Exception {
        dockerEndpointService.update(dockerEndpoint);
        clientFactory.refreshClientGroup();
        return ResponseModel.ok(Boolean.TRUE);
    }

    @ApiOperation("增加DockerEndpoint")
    @ApiOperationSupport(ignoreParameters = {"latestTestTime","createdAt","updatedAt"})
    @PostMapping("/save")
    public ResponseModel<Boolean> insertDockerEndpoint(@RequestBody DockerEndpoint dockerEndpoint) throws Exception {
        dockerEndpointService.save(dockerEndpoint);
        clientFactory.refreshClientGroup();
        return ResponseModel.ok(Boolean.TRUE);
    }
    @ApiOperation("Docker测试连接")
    @GetMapping("/{clientId}/test/connect")
    public ResponseModel<Boolean> testDockerEndpoint(@PathVariable String clientId) {
        final DockerClient client = clientFactory.get(clientId);
        client.pingCmd().exec();
        return ResponseModel.ok(Boolean.TRUE);
    }

}
